package com.mine.modules.vm.service.impl;

import com.mine.common.repository.ThumbnailRepository;
import com.mine.common.repository.base.Thumbnail;
import com.mine.modules.vm.service.IThumbnail;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class ThumbnailImpl implements IThumbnail {

    private final ThumbnailRepository thumbnailRepository;

    private final MongoTemplate mongoTemplate;

    private final GridFSBucket gridFSBucket;

    @Override
    public Thumbnail save(Thumbnail entity) {
        return thumbnailRepository.save(entity);
    }

    @Override
    public void deleteById(String id) {
        thumbnailRepository.deleteById(id);
    }

    @Override
    public void deleteBatch(String deviceId) {
        Query query = new Query(Criteria.where("id").regex(String.format("^%s_", deviceId)));
        List<String> ids = mongoTemplate.find(query, Thumbnail.class).stream().map(Thumbnail::getId).collect(Collectors.toList());
        thumbnailRepository.deleteAllById(ids);
    }

    @Override
    public Thumbnail findById(String id) {
        Optional<Thumbnail> optional = thumbnailRepository.findById(id);
        if (optional.isPresent())
            return optional.get();
        return null;
    }

    @Override
    public List<Thumbnail> findList() {
        return thumbnailRepository.findAll();
    }

    @Override
    public List<Thumbnail> findListByType(String type) {
        Query query = new Query(Criteria.where("type").is(type));
        return mongoTemplate.find(query, Thumbnail.class);
    }

    @Override
    public List<Thumbnail> findByIdStartingWith(String regionId) {
        Query query = new Query(Criteria.where("id").regex(String.format("^%s_", regionId)));
        return mongoTemplate.find(query, Thumbnail.class);
    }

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取文件输入流
        if(file == null){
            return "";
        }
        InputStream fileStream = file.getInputStream();
        // 创建上传选项
        GridFSUploadOptions options = new GridFSUploadOptions()
                .metadata(new org.bson.Document("type", "file"))
                .chunkSizeBytes(1024 * 512); // 设置每个 chunk 的大小，默认为 255 KB
        // 将文件保存到 GridFS 中
        ObjectId fileId = gridFSBucket.uploadFromStream(file.getOriginalFilename(), fileStream, options);
        // 存储文件元数据到数据库
        Thumbnail fileMetadata = new Thumbnail();
        fileMetadata.setId(fileId.toString());
        fileMetadata.setName(file.getOriginalFilename());
        fileMetadata.setContentType(file.getContentType());
        fileMetadata.setSize(file.getSize());
        mongoTemplate.save(fileMetadata);
        return fileId.toString();
    }

    @Override
    public byte[] downloadFile(String fileId) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectId id = new ObjectId(fileId);
        gridFSBucket.downloadToStream(id, outputStream);
        return outputStream.toByteArray();
    }


}
